'use strict';

const { Controller } = require('egg');
function verifyPassword(rule, value, callback) {
    const pattern = /^\w{6,18}$/;
    if (pattern.test(value)) {
        return callback();
    }
    callback({ message: `[ ${rule.field} ] 只能为6~18位的数字字母下划线` });
}
const ACCOUNT_RULE = {
    account: [{ required: true, message: '帐号不能为空' }, { validator: verifyPassword }],
    password: [{ required: true, message: '密码不能为空' }, { validator: verifyPassword }]
};
const PHONE_RULE = {
    phone: [{ require: true, message: '手机号不能为空' }, {
        validator(rule, value, callback) {
            const pattern = /^1[^1]\d{9}$/;
            if (pattern.test(value)) {
                return callback();
            }
            callback({ message: '手机号格式不正确' });
        }
    }]
};

class UserAccount extends Controller {
    // 发送短信验证码
    async sendSMS() {
        const { phone } = this.ctx.request.body;

        if (!await this.ctx.validate(PHONE_RULE, { phone })) {
            return;
        }

        const { status, verifyCode } = await this.app.saveVerifyCode({ phone });

        if (status === false) {
            return this.ctx.returnBody(403, '发送短信还在CD中', { verifyCode });
        }
        console.log(verifyCode);
        this.ctx.returnBody(200, '发送成功', { verifyCode });

        // 这里调用发送短信的服务
        // await this.service.mivaSMS.send({ phone, verifyCode })
        //     .then(_ => {
        //         this.ctx.returnBody(200, '发送成功', { verifyCode });
        //         VERIFYCODE[phone] = verifyCode;
        //         setTimeout(_ => delete VERIFYCODE[phone], 1000 * 60);
        //     })
        //     .catch(error => {
        //         this.ctx.returnBody(500, '发送失败', { error });
        //     });
    }

    // 手机号密码登录
    async loginPwd() {
        const { account, password: reqPwd } = this.ctx.request.body;
        // 参数验证
        if (!await this.ctx.validate(ACCOUNT_RULE, { account, password: reqPwd })) {
            return;
        }
        if (!await this.ctx.validate(PHONE_RULE, { phone: account })) {
            return;
        }
        // 执行登录服务
        const {
            status,
            token,
            message,
            password: resPwd
        } = await this.service.mivaAccount.login({ phone: account });
        // 验证用户是否存在
        if (token === null) {
            return this.ctx.returnBody(status, message);
        }
        // 验证密码
        if (resPwd !== this.app.md5(reqPwd)) {
            return this.ctx.returnBody(403, '密码错误');
        }
        // 登录成功
        this.ctx.returnBody(status, message, { token });
    }

    // 手机验证码登录
    async loginVer() {
        const { account: phone, verifyCode } = this.ctx.request.body;
        // 验证手机号
        if (!await this.ctx.validate(PHONE_RULE, { phone })) {
            return;
        }

        // 校验验证码
        if (!await this.app.isVerifyCode({ phone, verifyCode })) {
            return this.ctx.returnBody(400, '验证码错误');
        }

        // 执行登录服务
        const {
            status,
            token,
            message
        } = await this.service.mivaAccount.login({ phone });

        // 验证用户是否存在
        if (token === null) {
            // 执行注册服务
            const {
                status,
                token,
                message
            } = await this.service.mivaAccount.register({ account: phone, phone });
            return this.ctx.returnBody(status, message, token);
        }

        // 登录成功
        this.ctx.returnBody(status, message, { token });
    }

    // 获取用户个人信息
    async getSelfInfo() {
        const { user_id } = this.ctx.token || {};
        // 获取用户信息
        const result = await this.app.mysql.get('user_info', { user_id });
        this.ctx.returnBody(200, `获取用户个人信息成功`, result);
    }

    // 获取他人用户信息
    async getOtherInfo() {
        const { id } = this.ctx.query;
        // 获取用户信息
        const result = await this.app.mysql.get('user_info', { user_id: id });
        if (result === null) {
            return this.ctx.returnBody(404, `用户(${id}) 不存在`);
        }
        this.ctx.returnBody(200, `获取用户(${id}) 信息成功`, result);
    }

    // 修改密码
    async resetPassword() {
        const { phone, password, verifyCode } = this.ctx.request.body;
        const PASSWORD_RULE = {
            password: [{ required: true, message: '密码不能为空' }, { validator: verifyPassword }]
        };

        if (!await this.ctx.validate(PASSWORD_RULE, { password })) {
            return;
        }

        // 校验验证码
        if (!await this.app.isVerifyCode({ phone, verifyCode })) {
            return this.ctx.returnBody(400, '验证码错误');
        }
        // 修改密码操作
        await this.app.mysql.update('user', {
            password: this.app.md5(password),
            updated_at: new Date()
        }, {
            where: { phone }
        });

        this.ctx.returnBody(200, `密码修改成功`);
    }

    // 设置个人信息
    async resetUserInfo() {
        const { user_id } = this.ctx.token;

        // 获取用户信息
        const {
            nickname: nickname_old,
            birthday: birthday_old,
            sex: sex_old,
            qq: qq_old,
            wx: wx_old,
            description: description_old
        } = await this.app.mysql.get('user_info', { user_id });

        // 拿取前端传来的参数
        const {
            nickname = nickname_old,
            birthday = birthday_old,
            sex = sex_old,
            qq = qq_old,
            wx = wx_old,
            description = description_old
        } = this.ctx.request.body;

        // 修改操作
        await this.app.mysql.update('user_info', {
            nickname,
            birthday,
            sex,
            qq,
            wx,
            description,
            updated_at: new Date()
        }, {
            where: { user_id }
        });

        this.ctx.returnBody(200, `个人信息修改成功`);
    }

    // 设置用户头像
    async resetUserAvatar() {
        const { user_id } = this.ctx.token;
        const { avatar } = this.ctx.request.body;

        // 修改操作
        await this.app.mysql.update('user_info', {
            avatar,
            updated_at: new Date()
        }, {
            where: { user_id }
        });

        this.ctx.returnBody(200, `用户头像修改成功`);
    }

    //  后台登录
    async loginAdmin() {
        const { account, password } = this.ctx.request.body;

        if (!await this.ctx.validate(ACCOUNT_RULE, { account, password })) {
            return;
        }
        // 执行登录服务
        const { status, token, message } = await this.service.mivaAccount.login({ phone: account, password: this.app.md5(password) });
        if (status !== 200) {
            return this.ctx.returnBody(404, `用户不存在或密码错误`);
        }

        this.ctx.returnBody(status, message, { token });
    }

    // 获取用户列表
    async getUserList() {
        const { page = 0, size = 10, state = 1 } = this.ctx.query;
        const where = { state };
        const res_user = await this.app.mysql.select('user_info', {
            limit: Number(size),
            offset: Number(page),
            orders: [
                ['id', 'desc']
            ],
            where
        });

        this.ctx.returnBody(200, '查询成功', res_user);
    }
}

module.exports = UserAccount;
